package com.neo.code.lucene.demo01;

import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

import java.io.IOException;

/**
 * @author baiyp
 */
@Slf4j
public class Test {

    String indexDir = "/Users/mac/Lucene/index";
    String dataDir = "/Users/mac/Lucene/data";
    Indexer indexer;
    Searcher searcher;

    public static void main(String[] args) {
        Test tester;
        try {
            tester = new Test();
            tester.addDocs();
            tester.searchDocs("data_0?.txt");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addDocs() throws IOException {
        indexer = new Indexer(indexDir);
        long startTime = System.currentTimeMillis();
        indexer.addDocs(dataDir, new TextFileFilter());
        long endTime = System.currentTimeMillis();
        indexer.close();
        log.info("[indexing time]: {}ms", endTime - startTime);
    }

    private void deleteIndex(String name) throws IOException {
        indexer = new Indexer(indexDir);
        long startTime = System.currentTimeMillis();
        int numIndexed = indexer.deleteIndex(name);
        long endTime = System.currentTimeMillis();
        indexer.close();
        log.info("[deleting time]: {} ms", endTime - startTime);
    }

    private void searchDocs(String searchQuery) throws IOException, ParseException {
        searcher = new Searcher(indexDir);
        long startTime = System.currentTimeMillis();
        TopDocs hits = searcher.sortUsingCustom(searchQuery);
        long endTime = System.currentTimeMillis();
        log.info("[searching files]: {}", hits.totalHits);
        for (ScoreDoc scoreDoc : hits.scoreDocs) {
            Document doc = searcher.getDocument(scoreDoc);
            log.info("found -> " + doc.get(Constants.FILE_PATH) + "[" + scoreDoc.score + "]");
        }
        searcher.close();
        log.info("[searching time]: {} ms", endTime - startTime);
    }
}
